<template>
  <div class="receipt-order-edit-wrapper app-container">
    <div class="receipt-order-content">
      <el-form label-width="108px" :model="form" ref="form" :rules="rules">
        <!-- <el-form-item :label="$t('instorage.No')" prop="receiptOrderNo">
          <el-input class="w200" v-model="form.receiptOrderNo" placeholder="入库单号" disabled="disabled"></el-input>
        </el-form-item> -->
        <el-form-item :label="$t('instorage.type')" prop="receiptOrderType">
          {{ $t('inbound.E-commerce warehousing') }}
          <!-- <el-radio-group v-model="form.receiptOrderType">
            <el-radio-button v-for="dict in dict.type.wms_receipt_type" :key="dict.value" :label="dict.value">{{
                dict.label
              }}
            </el-radio-button>
          </el-radio-group> -->
        </el-form-item>
        <!-- <el-form-item :label="$t('common.supplier')" prop="supplierId">
          <WmsSupplierSelect v-model="form.supplierId"></WmsSupplierSelect>
        </el-form-item>
        <el-form-item :label="$t('fiance.amount')" prop="payableAmount" v-show="hasSupplier">
          <el-input-number v-model="form.payableAmount" :precision="2" :min="0" :label="$t('common.pleaseInput')"></el-input-number>
        </el-form-item> -->
        <el-form-item v-if="!isEdit" :label="$t('common.placeholderSelect')" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            :placeholder="$t('common.placeholderSelect')"
            clearable
            size="small"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.CabinetNo')" prop="cabinetNum">
          <el-input v-model="form.cabinetNum" :placeholder="$t('common.pleaseInput')" style="width: 36%"></el-input>
        </el-form-item>
        <!-- <el-form-item :label="$t('order.orderNo')" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" style="width: 36%"></el-input>
        </el-form-item> -->
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('common.placeholderRemark100')" rows="3" maxlength="100" type="textarea"
            show-word-limit="show-word-limit" style="width: 60%"></el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit" :label="$t('inbound.method')" prop="fromType">
          <el-select v-model="form.fromType">
            <el-option v-for="item in fromTypeList" :key="item.id" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.fromType === 1 && !isEdit" :label="$t('common.placeholderSelect')" prop="customerId">
          <WmsCustomerSelect v-model="form.customerId"></WmsCustomerSelect>
        </el-form-item>
        <el-form-item v-if="form.fromType === 2 && !isEdit" label="" prop="">
        <!-- <el-form-item v-if="form.fromType === 2 && !isFinishStatus" label="" prop=""> -->
          <el-button @click="importOrder">{{ $t('order.import') }}</el-button>
        </el-form-item>
        <div v-if="isFinishStatus || isEdit"  class="tc mt16">
          <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
          <el-button @click="submitForm" type="primary">{{ $t('common.save') }}</el-button>
        </div>
      </el-form>
      <div v-if="form.fromType === 1">
        <el-divider></el-divider>
        <div class="flex-center mb8">
          <div class="flex-one large-tip bolder-font">
            <el-row class="mb8 mt10" :gutter="10">
              <el-col :span="1.5">
                <div class="flex-one large-tip bolder-font">{{ $t('common.MaterialDetails') }}</div>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button size="small" type="success" plain="plain" icon="el-icon-delete-location"
                  @click="onBatchSetInventory">
                  批量设置仓库/库区
                </el-button>
              </el-col> -->
            </el-row>
          </div>
          <div class="ops">
            <el-button type="primary" plain="plain" size="small" @click="showAddItem">{{ $t('common.addSKU') }}</el-button>
            <!-- <el-button v-if="form.fromType === 2" type="primary" plain="plain" size="small" @click="showAddBox">{{ $t('common.addBOX') }}</el-button> -->
          </div>
        </div>
        <div class="table">
          <WmsTable :data="form.details" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column :label="$t('common.MaterialName')" align="center" prop="prod.itemName"></el-table-column>
            <el-table-column :label="$t('common.MaterialNo')" align="center" prop="prod.itemNo"></el-table-column>
            <el-table-column :label="$t('common.MaterialType')" align="center" prop="prod.itemType"></el-table-column>
            <el-table-column :label="$t('common.inventory')" align="center" prop="prod.stock"></el-table-column>
            <el-table-column :label="$t('common.planNumber')" align="center" prop="planQuantity" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.planQuantity" :placeholder="$t('common.pleaseInput')" :min="1" size="small"
                  @change="selectMoney" :max="2147483647"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.Warehouse/storage area')" align="center" width="200">
              <template slot-scope="scope">
                {{ scope.row.prod.warehouseName }}/{{ scope.row.prod.areaName }}
                <!-- <WmsWarehouseCascader v-model="scope.row.place" size="small"></WmsWarehouseCascader> -->
              </template>
            </el-table-column>
            <el-table-column :label="$t('fiance.amount')" align="center" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.money" :precision="2" @change="selectMoney" size="small" :min="0"
                  :label="$t('common.pleaseInput')"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.operation')" align="center">
              <template slot-scope="scope">
                <a class="red" @click="form.details.splice(scope.$index, 1)">{{ $t('common.del') }}</a>
              </template>
            </el-table-column>
          </WmsTable>
          <!-- <el-empty v-if="!form.details || form.details.length === 0" :image-size="48"></el-empty> -->
        </div>
        <div class="tc mt16">
          <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
          <el-button @click="submitForm" type="primary">{{ $t('common.save') }}</el-button>
        </div>
      </div>
    </div>
    <el-dialog :visible="modalObj.show" :title="modalObj.title" :width="modalObj.width" @close="modalObj.cancel">
      <template v-if="modalObj.component === 'add-item'">
        <item-select ref="item-select" :data="this.form.details" :warehouse-id="this.form.warehouseId" :tenant-id="this.form.customerId"></item-select>
      </template>
      <span slot="footer">
        <el-button v-if="modalObj.cancel" @click="modalObj.cancel">{{ $t('common.cancel') }}</el-button>
        <el-button v-if="modalObj.ok" type="primary" @click="modalObj.ok">{{ $t('common.confirm') }}</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible="boxModalObj.show" :title="boxModalObj.title" :width="boxModalObj.width"
      @close="boxModalObj.cancel">
      <BoxListComponent ref="boxList" :checkbox="checkbox" :allList="checkbox" :url="'/wms/omsPurchaseBox/list'"
        :methodType="'post'" :return-data="returnBoxData" :params="{
          pageSize: 100000,
        }" :styleBox="'height: calc(100vh - 210px);overflow: auto;'" @selection-change="handleSelectionBoxChange" />
      <span slot="footer">
        <el-button @click="boxModalObj.cancel">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="boxModalObj.ok">{{ $t('common.confirm') }}</el-button>
      </span>
    </el-dialog>
    <BatchWarehouseDialog :visible.sync="batchDialogVisible" :form-data.sync="batchForm"
      @confirmed="onBatchDialogFinished"></BatchWarehouseDialog>
    <ExportExcel ref="ExportExcelRef" :warehouse-id="form.warehouseId ? form.warehouseId : ''" :cabinet-num="form.cabinetNum ? form.cabinetNum : ''" />
  </div>
</template>

<script>
import NP from "number-precision";
import { mapGetters } from 'vuex';
import {
  addOrUpdateWmsReceiptOrder,
  getWmsReceiptOrder,
} from "@/api/wms/receiptOrder";
import { randomId } from "@/utils/RandomUtils";
import ItemSelect from "@/views/components/ItemSelect";
import BatchWarehouseDialog from "@/views/components/wms/BatchWarehouseDialog/index.vue";
import BoxListComponent from "@/views/components/wms/BoxList/index.vue";
import ExportExcel from "./exportExcel.vue";
import WmsAreaCascader from "@/components/WmsAreaCascader";

export default {
  name: "WmsReceiptOrder",
  props: {
    checkbox: {
      type: Boolean,
      default: true,
    }
  },
  components: {
    BatchWarehouseDialog,
    ItemSelect,
    BoxListComponent,
    ExportExcel,
    WmsAreaCascader
  },
  dicts: ["wms_receipt_type"],
  data() {
    return {
      ids: [],
      // 非多个禁用
      multiple: true,
      // 批量设置仓库/库区
      batchDialogVisible: false,
      batchForm: {
        place: [],
      },
      // 表单参数
      form: {
        details: [],
        payableAmount: 0.0,
        supplierId: null,
        fromType: 1,
      },
      // 表单校验
      rules: {
        customerId: [
          { required: true, message: this.$t('common.selectCustomer'), trigger: "change" },
        ],
      },
      modalObj: {
        show: false,
        title: "",
        width: "50%",
        component: null,
        model: {},
        ok: () => { },
        cancel: () => { },
      },
      boxModalObj: {
        show: false,
        title: "",
        width: "50%",
        component: null,
        model: {},
        ok: () => { },
        cancel: () => { },
      },
      hasSupplier: false,
      // 出入库方式 sku/箱子
      fromTypeList: [
        { label: "SKU", value: 1 },
        { label: this.$t('common.box'), value: 2 },
      ]
    };
  },
  watch: {
    "form.supplierId": {
      immediate: true,
      handler(value) {
        if (value) {
          this.hasSupplier = true;
        } else {
          this.hasSupplier = false;
        }
      },
    },
  },
  computed: {
    ...mapGetters(['warehouseList']),
    isEdit() {
      const bool = this.$route.query.isEdit;
      return bool
    },
    isFinishStatus() {
      const bool = this.$route.query.isFinish;
      return bool
    }
  },
  created() {
    const { id } = this.$route.query;
    if (id) {
      this.loadDetail(id);
    } else {
      this.reset();
    }
  },
  methods: {
    importOrder() {
      this.$refs.ExportExcelRef.openOdder();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    /** 批量设置仓库/库区 */
    onBatchSetInventory() {
      const { details } = this.form;
      if (!details || details.length === 0) {
        this.$modal.msgError(this.$t('common.pleaseAddSKU'));
        return;
      }
      // 未选中
      if (!this.ids.length) {
        this.$modal.msgError(this.$t('common.pleaseSelectSKU'));
        return;
      }
      this.batchDialogVisible = true;
    },
    onBatchDialogFinished() {
      this.batchDialogVisible = false;
      const [warehouseId, areaId, rackId] = this.batchForm.place || [];
      this.form.details.forEach((it) => {
        // 仅更新已选中
        if (this.ids.includes(it.id)) {
          it.place = [warehouseId, areaId, rackId].filter(Boolean);
        }
      });
    },
    /** 统计入库单金额 */
    selectMoney() {
      let sum = 0;
      this.form.details.map((item) => {
        if (
          !isNaN(parseFloat(item.money)) &&
          !isNaN(parseInt(item.planQuantity))
        ) {
          sum += item.money * item.planQuantity;
        }
        return item.money;
      });
      this.form.payableAmount = sum;
    },
    cancel() {
      // this.$tab.closeOpenPage({ path: "/wms/receiptOrder" });
      this.$router.go(-1)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        const details = this.form.details.map((it) => {
          if (it.place) {
            it.prod ? it.prod : it.prod = []
            it.prod.warehouseId = it.place[0];
            it.prod.areaId = it.place[1];
            it.prod.rackId = it.place[2];
          } else {
            it.prod.warehouseId = null;
            it.prod.areaId = null;
            it.prod.rackId = null;
          }
          return {
            itemId: it.prod.id,
            rackId: it.prod.rackId,
            areaId: it.prod.areaId,
            money: it.money,
            warehouseId: it.prod.warehouseId,
            planQuantity: it.planQuantity,
            realQuantity: it.realQuantity,
            receiptOrderStatus: it.receiptOrderStatus,
            delFlag: 0,
          };
        });
        const wareIds = this.form.warehouseId || []
        const type = this.form.fromType === 1 ? 'SKU' : "BOX"
        // const req = { ...this.form, warehouseId: wareIds[0] || '', areaId: wareIds[1] || '', details, type: type };
        let req = {}
        if(this.isFinishStatus && this.form.fromType === 2) {
           req = { ...this.form, warehouseId: wareIds[0] || '', areaId: wareIds[1] || '', type: type };
        } else {
           req = { ...this.form, warehouseId: wareIds[0] || '', areaId: wareIds[1] || '', details, type: type };
        }
        // console.log('req', req)
        // return
        addOrUpdateWmsReceiptOrder(req).then((response) => {
          this.$modal.msgSuccess(this.$t('common.succcessInfo'));
          this.cancel();
        });
      });
    },
    loadDetail(id) {
      getWmsReceiptOrder(id).then((response) => {
        const { details, items } = response;
        const map = {};
        (items || []).forEach((it) => {
          map[it.id] = it;
        });
        details && details.forEach((it) => (it.prod = map[it.itemId]));
        response.type === 'SKU' ? response.fromType = 1 : response.fromType = 2
        this.form = {
          ...response,
          details,
        };
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        receiptOrderNo: "R-" + randomId(),
        receiptOrderType: 1,
        customerId: null,
        supplierId: null,
        orderNo: null,
        receiptOrderStatus: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        details: [],
      };
      this.resetForm("form");
    },
    confirmSelectItem() {
      const value = this.$refs["item-select"].getRightList();
      this.form.details = value.map((it) => {
        return {
          id: it.id,
          prod: it,
          planQuantity: null,
          realQuantity: null,
          place: [],
          receiptOrderStatus: 0,
          delFlag: 0,
        };
      });
      this.closeModal();
    },
    closeModal() {
      this.modalObj.show = false;
    },
    closeBoxModal() {
      this.boxModalObj.show = false;
    },
    confirmSelectBox() {
      // 使用filter方法筛选出不同的记录
      const differentRecords = this.chooseList.filter(obj2 => !this.form.details.some(obj1 => obj1.id === obj2.id));
      // 使用some方法检查是否存在相同id的记录
      const hasSameId = this.chooseList.some(obj2 => this.form.details.some(obj1 => obj1.id === obj2.id));
      // 如果存在相同id的记录，则给出提示
      if (hasSameId) {
        console.log("存在相同id");
      }
      // 将不同的记录推送到array1中
      this.form.details.push(...differentRecords);
      this.closeModal();
    },
    showAddBox() {
      try {
        this.$refs["item-select"].initDetailsList(this.form.details);
      } catch (err) { }
      const ok = () => this.confirmSelectBox();
      const cancel = () => this.closeBoxModal();
      this.boxModalObj = {
        show: true,
        title: this.$t('common.addBOX'),
        width: "50%",
        component: "add-item",
        model: {},
        ok,
        cancel,
      };
      this.getBoxList();
    },
    showAddItem() {
      if (!this.form.warehouseId) {
        this.$message.warning(this.$t('common.pleaseSelectWarehouseing'))
      } else {
        try {
          this.$refs["item-select"].initDetailsList(this.form.details);
        } catch (err) { }
        const ok = () => this.confirmSelectItem();
        const cancel = () => this.closeModal();
        this.modalObj = {
          show: true,
          title: this.$t('common.addSKU'),
          width: "50%",
          component: "add-item",
          model: {},
          ok,
          cancel,
        };
      }
    },
    getBoxList() {
      this.$nextTick(() => {
        this.$refs.boxList.getList();
      });
    },
    returnBoxData(data) {
      if (data.content) {
        return data.content;
      }
    },
    handleSelectionBoxChange(v) {
      let c = 0;
      this.chooseList = v.map((r) => {
        let v = NP.times(r.boxHigh, r.boxStrong, r.boxWide);
        c = NP.plus(c, v);
        return r;
      });
    }
  },
};
</script>
<style lang="stylus">
.receipt-order-edit-wrapper
  .receipt-order-content
    width 70%
    min-width 900px
    margin 0 auto
</style>
